

# 以Mixin结尾的类是封装了特定的
# 功能  需要时进行继承
# 定义验证jwt的扩展类
from django.conf import settings
from django.http import JsonResponse
import jwt

from models import User


class LoginValidMixin(object):
    # 视图匹配后会找as_view后调用dispatch后get  post  ....
    # 所以重写dispatch
    def dispatch(self,request,*args,**kwargs):
        # 接受请求保温头中的信息

        token = request.META['HTTP_AUTHORIZATION']
        if len(token) <= 4:
            return JsonResponse({"msg":"缺少身份信息"},status=401)
        token=token[4:]
        try:
            payload = jwt.decode(token,settings.SECRET_KEY)
        except:
            return JsonResponse({"msg":"身份信息无效"},status=401)
        # 获取用户id
        user_id = payload.get("id")
        user = User.objects.get(pk=user_id)
        # 在后续视图中可以正常访问当前用户
        request.user = user
        return super().dispatch(request, *args, **kwargs)


        # if not request.user.is_authenticated:
        #     return self.handle_no_permission()
        # return super(LoginRequiredMixin, self).dispatch(request, *args, **kwargs)

        # 验证请求信息
        pass
